<template>
  <base-breadcrumb :title="title">
    <!-- 质量创优申报资料库编辑 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}" id="base-breadcrumb" style="position: relative">
      <a-spin :spinning="loading">
        <a-card :bordered="false" style="margin-bottom: 80px">
          <title-name title="基础信息"></title-name>
          <custom-form :formList="formList" :form="form" :editModel="editModel == 0 ? 'V' : ''"
                       @selectOrg="selectOrg">
            <template #recordName>
              <div v-if="editModel == 0" style="margin-top: -3px">{{ form.recordName }}</div>
              <a-row v-else type="flex" align="middle">
                <div :style="{ width: editModel == 0 ? '100%' : 'calc(100% - 108px)' }">
                  <BaseInput v-model="form.recordName" disabled></BaseInput>
                </div>
                <ChooseModel v-if="editModel != 0" :form="form" />
              </a-row>
            </template>
          </custom-form>
          <!-- 新增时不显示 -->
          <template v-if="editModel != 2">
            <title-name title="相关附件"></title-name>
            <a-row :gutter="32">
              <a-col :span="4" style="border-right: 1px solid #d9d9d9">
                <tree-search
                  ref="treeSearch"
                  emptyDescription="暂无信息"
                  :api="api"
                  :isAll="true"
                  :selected-keys.sync="selectedKeys"
                  :select-options.sync="selectOptions"
                  :init-expand-all="false"
                  @loader="search"
                  @submitForm="submitForm"
                >
                  <div v-if="editModel != 0" slot="footer" slot-scope="scope" ref="btnBox" align="center">
                    <a-button size="small" :disabled="selectedKeys && selectedKeys.length < 1" class="btn_right" type="primary" @click="scope.handleOperate(0)"> 添加 </a-button>
                    <a-button size="small" :disabled="(selectedKeys && selectedKeys.length < 1) || !selectOptions.parentId" class="btn_right" type="primary" @click="scope.handleOperate(1)"> 编辑 </a-button>
                    <!-- 添加跟节点不可删除 -->
                    <a-button size="small" type="danger" :disabled="(selectedKeys && selectedKeys.length < 1) || !selectOptions.parentId" @click="handleRemoveNode"> 删除 </a-button>
                  </div>
                </tree-search>
              </a-col>
              <a-col :span="20">
                <BTableUpload
                  ref="BTableUpload"
                  :btnAttrs="{ disabled: (selectedKeys && selectedKeys.length < 1) || !selectOptions.parentId }"
                  btnName="添加附件"
                  v-model="fileArrays"
                  :disabled="editModel == 0"
                  business-code="QM11"
                  @input="handleUpload"
                />
              </a-col>
            </a-row>
          </template>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box tool-btns--fixed page-btn-right-top">
        <a-button v-if="editModel != 0" :loading="loading" type="primary" class="button_right" @click="handleSubmit">提交</a-button>
        <a-button type="primary" @click="$multiTab.close()">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { excellenceApplication } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import ChooseModel from '../components/ChooseModel' // 选择奖项信息
import TreeSearch from '@/components/businessComponents/TreeSearch' // 树搜索
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    ChooseModel,
    TreeSearch
  },
  data() {
    return {
      loading: false,
      editModel: 0,
      form: {
        tree: {}, // 附件树目录
        filler: void 0, // 创建人
        fillerDate: void 0, // 创建时间
        viewName: ""
      },
      fileArrays: [],
      selectedRowKeys: [], // 奖项信息选中id集合
      selectedRow: [], // 奖项信息选中对象集合
      dataSource: [], // 奖项信息列表
      selectedKeys: [], // 树选中节点id集合
      selectOptions: {}, // 树选中节点对象
      rules: {
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        recordName: [{ required: true, message: '请选择奖项名称', trigger: 'change' }],
        declareEmployeeName: [{ required: true, whitespace: true, message: '请输入申报人', trigger: 'change' }],
        declareDate: [{ required: true, message: '请选择申报时间', trigger: 'change' }]
      },
      titles: ['查看质量创优申报资料', '编辑质量创优申报资料', '新增质量创优申报资料']
    }
  },
  mounted() {
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.init()
    } else {
      this.form.filler = this.$userInfo()?.name // 默认填报人
      this.form.fillerDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
    }
  },
  watch: {
    'form.recordName'() {
      this.$nextTick(() => {
        this.$refs.ruleForm?.validateField('recordName')
      })
    }
  },
  computed: {
    // 节点api
    api() {
      return {
        getList: () => Promise.resolve({ data: this.form.tree ? [this.form.tree] : [] }), // 获取树节点列表
        create: (e) => excellenceApplication.addNode(e), // 添加树节点
        update: (e) => excellenceApplication.updateNode(e), // 编辑树节点
        delete: (e) => excellenceApplication.deleteNode(e) // 删除树节点
      }
    },
    // 表单配置项
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          disabled: this.editModel == 0,
          isNoBorder: this.editModel == 0,
          viewName: "viewName",
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '所属分公司',
        //   viewName: 'branchComName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   viewName: 'projectName',
        //   attrs: {
        //     keyValue: 'branchComId',
        //     autoSelected: this.editModel == 2,
        //     isClear: this.editModel == 2,
        //     form: this.form
        //   }
        // },
        {
          keyName: 'recordName',
          slot: true,
          label: '奖项名称'
        },
        {
          keyName: 'declareEmployeeName',
          type: 'a-input',
          label: '申报人'
        },
        {
          keyName: 'declareDate',
          type: 'a-month-picker',
          placeholder: '请选择月份',
          label: '申报时间',
          attrs: {
            valueFormat: 'YYYY-MM'
          }
        },
        {
          keyName: 'filler',
          type: 'a-input',
          disabled: true,
          label: '创建人'
        },
        {
          keyName: 'fillerDate',
          type: 'a-date-picker',
          disabled: true,
          label: '创建时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
    },
    /**
     * @description: 停用节点
     */
    handleRemoveNode() {
      let that = this
      let e = that.selectOptions
      that.$confirm({
        title: '温馨提示',
        content: `确认删除？`,
        okText: '确认',
        cancelText: '关闭',
        onOk() {
          return that.api.delete({ id: e.id }).then((res) => {
            if (res.data.code == 200) {
              that.$message.success('删除成功！')
              that.$refs.treeSearch.selectedKeys = [that.form.tree.id]
              that.$refs.treeSearch.selectOptions = that.form.tree
              that.init()
            }
          })
        }
      })
    },
    /**
     * @description: 附件操作
     * @param {Array} e：附件列表
     */
    async handleUpload(e) {
      let form = {
        fileArrays: e,
        id: this.selectedKeys[0]
      }
      const res = await excellenceApplication.addFile(form)
      if (res.code === 200) {
        // 刷新附件table
        this.search(false)
      }
    },
    /**
     * @description: 节点操作
     * @param {String,Number} editModel：操作类型：0 新增；1 编辑
     * @param {Object} form：表单
     */
    submitForm(editModel, form) {
      let name = ['create', 'update'][editModel] // 根据操作切换url地址
      let id = ['parentId', 'id'][editModel] // 新增传parentId,编辑传id
      let forms = {
        name: form.name,
        [id]: form.id
      }
      // 提交表单
      this.api[name](forms)
        .then((res) => {
          this.$refs.treeSearch.$refs.dialogNode.loading = false
          if (res.code === 200 || res.data.code === 200) {
            this.$message.success(['添加', '编辑'][editModel] + '成功！')
            this.$refs.treeSearch.visible = false // 关闭弹窗
            this.init()
          }
        })
        .catch(() => {
          this.$refs.dialogNode.loading = false
        })
    },
    /**
     * @description: 初始化
     */
    init() {
      this.loading = true
      excellenceApplication
        .getDetail({ id: this.id })
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            // 格式化奖项
            if (res.data.record) {
              res.data.recordName = res.data.record.name
              res.data.recordId = res.data.record.id
            }
            this.form = res.data
            this.form.viewName = this.form.branchComName + '/' + this.form.projectName
            this.$nextTick(() => {
              this.$refs.treeSearch.getList().then(() => {
                if (this.selectedKeys?.length) {
                  // 获取列表
                  this.search()
                }
              })
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * @description: 检索附件
     * @param {Boolean} e：是否显示加载框
     */
    async search(e = true) {
      if (e) {
        this.$refs.BTableUpload.loading = true
      }
      const res = await excellenceApplication.getDetailsNode({ id: this.selectedKeys[0] }).catch(() => {
        if (e) {
          this.$refs.BTableUpload.loading = false
        }
      })
      if (e) {
        this.$refs.BTableUpload.loading = false
      }
      if (res.code === 200) {
        this.fileArrays =
          res.data?.fileArrays?.sort(function (a, b) {
            return new Date(a.createTime).getTime() - new Date(b.createTime).getTime()
          }) || []
      }
    },
    /**
     * @description: 奖项信息复选项改变
     * @param {*} selectedRowKeys：选中项
     */
    onSelectChange(selectedRowKeys, selectedRow) {
      // console.log(selectedRowKeys, selectedRow)
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    /**
     * @description: 关联奖项信息后回调
     */
    handleConfirm() {
      this.$set(this.form, 'name', this.selectedRow?.[0]?.name)
      this.$set(this.form, 'part', this.selectedRow?.[0]?.part)
      this.$set(this.form, 'subcontractor', this.selectedRow?.[0]?.subcontractor)
      this.$set(this.form, 'subcontractorId', this.selectedRow?.[0]?.subcontractorId)
      // 重置搜索表单
      this.$refs.searchData?.form.resetFields()
      this.visible = false
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      let name = ['updatePost', 'create'][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          that.$confirm({
            title: '温馨提示',
            content: '确定提交，提交后不可撤回？',
            onOk: () => {
              let form = that.$clone(that.form)
              // 新增时
              if (that.editModel == 2) {
                // 根据登陆人级别传不同的组织id
                form[{ CO: 'companyId', BC: 'branchComId' }[that.$currentPost().code]] = that.$currentPost().id
                // 添加登陆人级别
                form.submitLevel = that.$currentPost().code
              }
              return excellenceApplication[name](form).then((res) => {
                if (res.code === 200 || res.data.code === 200) {
                  that.$message.success('提交成功！')
                  // 编辑时才关闭，新增成功立即进入编辑模式
                  if (that.editModel == 1) {
                    that.$multiTab.close()
                  } else {
                    // 设置为编辑
                    that.editModel = 1
                    // 设置业务id
                    that.id = res.data.id
                    // 格式化奖项
                    if (res.data.record) {
                      res.data.recordName = res.data.record.name
                      res.data.recordId = res.data.record.id
                    }
                    // 映射表单
                    that.form = res.data
                    // 请求树列表
                    that.$nextTick(() => {
                      that.$refs.treeSearch.getList()
                    })
                  }
                }
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-calendar-picker {
  width: 100% !important;
}
</style>
